package smashedapples.air.sqlite
{
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	
	import mx.collections.ArrayCollection;
	
	import smashedapples.core.NonVisualComponent;

	public class SQLiteQuery extends NonVisualComponent
	{
		public function SQLiteQuery()
		{
			super();
		}
		
		
		[Bindable] public var result:DataCollection;
		
		[Bindable] public var tableName:String;
		
		[Inspectable(enumeration="true,false",defaultVallue="true")]
		public var autoUpdate:Boolean = true;
		
		public var db:SQLiteDB;
		
		public var select:String = "*";
		
		public var orderBy:String;
		
		public var parameters:Object = {};
		
		public function execute( parameters:Object = null ):void
		{
			this.parameters = ( parameters == null ) ? {} : parameters;
				
			var table:SQLiteTable = db.getTableByName( this.tableName );
			
			var statement:SQLStatement = new SQLStatement();

				statement.sqlConnection = this.db.connection;

				statement.text = SQLiteCommandBuilder.createSelectStatement( this );

				statement = SQLiteCommandBuilder.setStatementParameters( statement, this.parameters );
				
				// event listeners
				statement.addEventListener( SQLEvent.RESULT, handleResultEvent );
				statement.addEventListener( SQLErrorEvent.ERROR, handleErrorEvent );
				// debug				
				db.addToDebug( {statement:statement.text,params:statement.parameters} );
				// execute
				statement.execute();
		}
		
		public function executeAutoUpdate():void
		{
			if( this.autoUpdate )
				this.execute( this.parameters );
		}
		
		private function handleResultEvent( event:SQLEvent ):void
		{	
			var statement:SQLStatement = event.target as SQLStatement;
			var result:SQLResult = statement.getResult(); 
			var data:Array = ( result.data == null) ? [] : result.data;
			this.result = new DataCollection( data );
		}
		
		private function handleErrorEvent( event:SQLErrorEvent ):void
		{
			db.addToDebug( event );
		}
		
		
		
		
	}
}